//
//  SLPreferencesSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/23.
//

#import "SLBridgeDetailVC.h"
#import "SLUpdateFirmVC.h"
#import "SLPreferencesSetCell.h"
#import "SLBridgeLockListVC.h"
#import "SLSetBridgeWifiVC.h"
static  NSString *const kCellId = @"SLPreferencesSetCell";

@interface SLBridgeDetailVC ()<UITableViewDelegate,UITableViewDataSource>{
    BOOL _isFirstLoad;
}
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@end

@implementation SLBridgeDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    _isFirstLoad = YES;
    [self loadData:YES];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Bridge management");
    [self confiDatas];
    [self.view addSubview:self.tableView];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 120)];
    ZKBaseButton *sureBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(0, 35, kScreenWidth-40, 50);
    sureBtn.btnStyle = 2;
    [sureBtn setTitle:kLocalString(@"Delete bridge") forState:UIControlStateNormal];
    [footView addSubview:sureBtn];
    [sureBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableFooterView = footView;
}

-(void)deleteAction{
    [SLTipAlertView showWith:kLocalString(@"Are you sure you want to delete this lock?") content1:kLocalString(@"This action will completely reset the lock to its factory settings. All stored fingerprints and e-keys will be permanently erased and cannot be recovered.") content2:@"" doneBtn:kLocalString(@"Delete and reset lock") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
        if (index == 0) {
            return;
        }
        //1.先确认设备是否在线
        [ZCTool showLoadingOnKeyWindow];
        //2.服务器解绑
        [self deleteBridge:NO];
    }];
}

-(void)deleteBridge:(BOOL)isForce{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"deviceNo":kCurClickDevice.deviceNo}];
    if (isForce) [params setObject:@"jump" forKey:@"way"];
    [ZKHttpManager postWithPath:@"/msl_user/UnBindDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString    * _Nonnull serMessage) {
        if (!isSuccessed) {
            if ([code isEqualToString:@"610"] && !isForce) {
                [self deleteBridge:YES];
            }else{
                [ZCTool hideLoadingOnKeyWindow];
                kShowToast(serMessage);
            }
            return;
        }
        kShowToast(@"Delete success!");
        kNotifyRefreshDevcieList;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }];
}

-(void)loadData:(BOOL)needShowHud{
    if (needShowHud) [ZCTool showLoadingOnKeyWindow];
    NSString *url = [NSString stringWithFormat:@"/msl_user/getDevInfo/%@",kCurClickDevice.deviceNo];
    [ZKHttpManager getWithPath:url params:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        //更新页面
        NSDictionary *data = result[@"result"];
        kCurClickDevice.firmware = data[@"version"];
        kCurClickDevice.rssi = kSTRING(data[@"rssi"]);
        kCurClickDevice.wifiName = kSTRING(data[@"wifiName"]);
        kCurClickDevice.macAddress = kSTRING(data[@"macAddr"]);
        [self refreshSubViews];
        if (self->_isFirstLoad) {
            self->_isFirstLoad = NO;
            [self checkUpdateInfo:data[@"version"]];
        }
    }];
}

//检查升级
-(void)checkUpdateInfo:(NSString *)version{
    [ZCTool checkUpdateInfo:version finish:^(BOOL needUpdate, id  _Nonnull updateInfo) {
        if (needUpdate) {
            [self showUpdateAlertView:updateInfo];
        }
    }];
}

-(void)showUpdateAlertView:(NSDictionary *)updateInfo{
    if ([ZCTool getCurrentUIVC] != self) return;
        
    NSString *desc = kLocalString(@"Update available for <1> New ver <2>");
    desc = [desc stringByReplacingOccurrencesOfString:@"<1>" withString:kCurClickDevice.productName];
    desc = [desc stringByReplacingOccurrencesOfString:@"<2>" withString:[NSString stringWithFormat:@"%@",updateInfo[@"serverVersion"]]];
    [SLTipAlertView showWith:kLocalString(@"New firmware update available") content1:desc content2:@"" doneBtn:kLocalString(@"Go to update") cancelBtn:kLocalString(@"Remind me later") action:^(NSInteger index) {
        if (index == 1) {
            SLUpdateFirmVC *vc = [[SLUpdateFirmVC alloc] init];
            vc.updateInfo = updateInfo;
            kWeakSelf(self);
            [vc setUpdateSuccessBlock:^{
                [weakself loadData:NO];
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}

-(void)confiDatas{
    [self.dataArray removeAllObjects];
    NSArray *sectionTitle1 = @[kLocalString(@"Name"),kLocalString(@"Wi-fi"),kLocalString(@"Model"),kLocalString(@"Mac"),kLocalString(@"Version")];
    NSString *wifiName = kReplace(kCurClickDevice.wifiName, kLocalString(@"Disconnected"));
    NSArray *sectionContent1 = @[kCurClickDevice.deviceName,wifiName,kReplace(kCurClickDevice.model, @"-"),kSTRING(kCurClickDevice.macAddress),kSTRING(kCurClickDevice.firmware)];
  
    NSArray *sectionTitle2 = @[kLocalString(@"Connected devices")];
    NSArray *sectionContent2 = @[@""];
    
    NSMutableArray *section1 = [NSMutableArray new];
    NSMutableArray *section2 = [NSMutableArray new];
    
    [sectionTitle1 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull
                                                stop) {
        NSString *content = sectionContent1[idx];
        NSMutableDictionary *info = [NSMutableDictionary new];
        [info setObject:title forKey:@"title"];
        [info setObject:content forKey:@"content"];
        [info setObject:@"0" forKey:@"type"];
        if ([title isEqualToString:kLocalString(@"Name")]) {
            [info setObject:@"3" forKey:@"type"];
        }else if ([title isEqualToString:kLocalString(@"Wi-fi")] || [title isEqualToString:kLocalString(@"Version")]){
            [info setObject:@"1" forKey:@"type"];
        }
        [section1 addObject:info];
    }];
    
    [sectionTitle2 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *info = [NSMutableDictionary new];
        NSString *content = sectionContent2[idx];
        [info setObject:title forKey:@"title"];
        [info setObject:content forKey:@"content"];
        [info setObject:@"1" forKey:@"type"];
        [section2 addObject:info];
    }];
    
    [_dataArray addObject:section1];
    [_dataArray addObject:section2];
}

-(void)refreshSubViews{
    [self confiDatas];
    [_tableView reloadData];
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionArr = _dataArray[section];
    return sectionArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLPreferencesSetCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *info = _dataArray[indexPath.section][indexPath.row];
    NSArray *section = _dataArray[indexPath.section];
    cell.line.hidden = indexPath.row == section.count-1;
    NSString *type = info[@"type"];
    cell.contentLbl.textColor = KColor_placeholdar;
    cell.list.image = nil;
    cell.changeBtn.hidden = YES;
    cell.titleLbl.text = info[@"title"];
    cell.contentLbl.text = info[@"content"];
    cell.iconRightSpace.constant = 0;
    if ([type isEqualToString:@"0"]) {
    }else if ([type isEqualToString:@"1"]){
        cell.iconRightSpace.constant = 15;
        cell.list.image = [UIImage imageNamed:@"icon_list_arrow"];
    }else if ([type isEqualToString:@"3"]){
        cell.iconRightSpace.constant = 15;
        cell.list.image = [UIImage imageNamed:@"icon_edit_access"];
        cell.contentLbl.textColor = KColor_Y;
    }
    if ([cell.contentLbl.text isEqualToString:kLocalString(@"Disconnected")]) {
        cell.contentLbl.textColor = KRedColor;
    }
   
    [cell.contentView setRoundedCorners:0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    if (indexPath.row == section.count-1) {
        if (section.count == 1) {
            [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
        }else{
            [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
        }
    }else if (indexPath.row == 0){
        [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerTopLeft | UIRectCornerTopRight frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    }
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 20);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *info = _dataArray[indexPath.section][indexPath.row];
    NSString *title = info[@"title"];
    if ([title isEqualToString:kLocalString(@"Version")]) {
        SLUpdateFirmVC *vc = [[SLUpdateFirmVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if([title isEqualToString:kLocalString(@"Name")]){
        [self showInputView];
    }else if([title isEqualToString:kLocalString(@"Connected devices")]){
        SLBridgeLockListVC *vc = [[SLBridgeLockListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if([title isEqualToString:kLocalString(@"Wi-fi")]){
        SLSetBridgeWifiVC *vc = [[SLSetBridgeWifiVC alloc] init];
        vc.bridgeDetailVc = self;
        kWeakSelf(self);
        [vc setRefreshBlock:^{
           //刷新
            [weakself loadData:YES];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)showInputView{
    __weak SLInputAlertView *alert = [SLInputAlertView viewFromXIB];
    alert.titleLbl.text = kLocalString(@"Edit bridge name");
    [alert.tf setPlaceholderWithPlaceholderText:kLocalString(@"Edit bridge name") withColor:KColor_placeholdar withFont:kFont(16)];
    [alert setBtnBlock:^(NSString *text, NSInteger btnIndex) {
        if (btnIndex == 2) {
            [alert removeFromSuperview];
            return;
        }
        if (btnIndex == 1) {
            if (text.length == 0) {
                kShowToast(@"Enter bridge name");
                return;
            }
            [alert removeFromSuperview];
            [ZCTool showLoadingOnKeyWindow];
            NSDictionary *params = @{@"deviceName":text};
            [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                [ZCTool hideLoadingOnKeyWindow];
                if (!isSuccessed) {
                    kShowToast(message);
                    return;
                }
                //修改成功
                kCurClickDevice.deviceName = text;
                [self refreshSubViews];
                kNotifyRefreshDevcieList;
            }];
        }
    }];
    [kAppWindow addSubview:alert];
}


-(void)showSuccessViews{
    __weak SLSuccessAlertView *alert = [SLSuccessAlertView viewFromXIB];
    alert.contentLbl.text = kLocalString(@"App cache has been deleted successfully.");
    [alert setBtnBlock:^(NSInteger btnIndex) {
        [alert removeFromSuperview];
    }];
    [kAppWindow addSubview:alert];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, SafeAreaTopHeight,kScreenWidth-40,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

@end
